package com.pomr.service.common.impl;

import com.pomr.dao.base.BaseDao;
import com.pomr.entity.bigscr.BindInfo;
import com.pomr.entity.bigscr.PersonInfo;
import com.pomr.model.data.MonitorMessage;
import com.pomr.model.equipmentstorage.*;
import com.pomr.model.health.PersonRecord;
import com.pomr.model.sys.User;
import com.pomr.service.common.BigScrService;
import com.pomr.util.common.DateUtil;
import com.pomr.util.common.ResponseData;
import org.apache.commons.lang.StringUtils;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * @作者：wgchao
 * @时间：18:09 2019/6/13 0013
 * @用途：
 **/
@Service
public class BigScrServiceImpl implements BigScrService {
    @Autowired
    @Qualifier("baseDaoImpl")
    private BaseDao baseDao;
    @Autowired
    private SessionFactory sessionFactory;

    public Session session(){
        return sessionFactory.getCurrentSession();
    }



    @Override
    public List<PersonInfo> searchPersonInfo(int curr, int limit) throws Exception{
        if(curr <= 1){
            curr = 1;
        }
        if(limit <= 0){
            limit = 10;
        }
        //获取前一周的时间
        String wdate = DateUtil.datebackweek();

        String sql = "SELECT record.name,record.idcard,record.birth,record.sex_id, receive.emanufacturerName, receive.equipmentName, receive.especification, lsum.sumb " +
                "FROM equipment_receive receive, equipment_leader leader, person_record record, " +
                "(SELECT md.leader_id, COUNT(1) sumb FROM monitoring_data md where md.monitorTime>='"+wdate+"' group by md.leader_id) lsum " +
                "WHERE lsum.leader_id = leader.id AND leader.receive_id = receive.id AND record.id = leader.record_id " +
                "GROUP BY record.name,record.idcard,record.birth,record.sex_id, receive.emanufacturerName, receive.equipmentName, receive.especification " +
                "ORDER BY lsum.sumb desc limit "+(curr-1)+","+limit;
        List res = session().createSQLQuery(sql).list();
        if(res!=null && !res.isEmpty()){
            return PersonInfo.instancelist(res);
        }
        return null;
    }

    @Override
    public List<MonitorMessage> searchMonitorByPerson(String idcard, String eName, String spec) throws Exception {

        //获取前一周的时间
        String wdate = DateUtil.datebackweek();

        String sql = "SELECT * from monitoring_data md where md.leader_id IN ( " +
                "SELECT leader.id " +
                "from equipment_leader leader, person_record record, equipment_receive receive " +
                "where leader.record_id = record.id AND receive.id = leader.receive_id " +
                "AND record.idcard='"+idcard+"' " +
                "AND receive.equipmentName='"+eName+"' AND receive.especification='"+spec+"') " +
                "AND md.monitorTime>='"+wdate+"' "+
                "ORDER BY md.monitorTime DESC";
        List<MonitoringData> monitoringDatas = session().createSQLQuery(sql).addEntity(MonitoringData.class).list();
        if(monitoringDatas!=null && !monitoringDatas.isEmpty()){
            List<MonitorMessage> monitors = new ArrayList<MonitorMessage>();
            for(int k=0; k<monitoringDatas.size(); k++){
                monitors.add(new MonitorMessage(monitoringDatas.get(k)));
            }
            return monitors;
        }
        return null;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseData bindfromsm(BindInfo bindInfo) throws Exception {
        //查询用户是否存在
        List<PersonRecord> personRecords = baseDao.findByHql("from PersonRecord pr where pr.idcard='"+bindInfo.getIdcard()+"'");
        PersonRecord personRecord = null;
        if(personRecords==null || personRecords.isEmpty()){
            System.out.println("用户在系统中不存在，先注册档案");
            personRecord = new PersonRecord();
            personRecord.setName(bindInfo.getUserName());
            personRecord.setIdcard(bindInfo.getIdcard());
            int pid = 0;
            if((pid=baseDao.addNumKey(personRecord))<=0){
                throw new Exception("注册档案失败");
            }
            personRecord.setId(pid);
        }else{
            personRecord = personRecords.get(0);
        }

        //查询设备是否存在
        List<EquipmentStorageDetail> equipmentStorageDetails = baseDao.findByHql("from EquipmentStorageDetail edetail where edetail.sN='"+bindInfo.getSn()+"'");
        if(equipmentStorageDetails==null || equipmentStorageDetails.isEmpty()){
            throw new Exception("设备不存在");
        }
        EquipmentStorageDetail equipmentStorageDetail = equipmentStorageDetails.get(0);
        //查询设备是否存在已经绑定了SIM卡
        List<DeviceMatch> deviceMatches = baseDao.findByHql("from DeviceMatch where equipmentdetail.sN='"+bindInfo.getSn()+"' and (noBindTime = null or noBindTime='')");
        if(deviceMatches==null || deviceMatches.isEmpty()){
            throw new Exception("设备没有绑定SIM卡，请先绑定后在领用");
        }
        DeviceMatch deviceMatch = deviceMatches.get(0);
        //查询用户是否已经领用了同类型的设备
        String ishas = "from Receive where record.id="+personRecord.getId()+" and receiveTime=null and " +
                "match.equipmentdetail.equipmentStorage.equipment.kind.id=" +
                "(select dm.equipmentStorage.equipment.kind.id from EquipmentStorageDetail dm where dm.id="+equipmentStorageDetail.getId()+")";
        List rs = baseDao.findByHql(ishas);
        if(rs!=null && !rs.isEmpty()){
            throw new Exception("用户已经领取了该类型的设备，请退还后在申请");
        }
        //查看设备、SIM卡是否已被使用
        String issb = "from Receive where match.equipmentdetail.id="+equipmentStorageDetail.getId()+" "
                + "and (receiveTime = null or receiveTime = '')";
        List<Object> rec = baseDao.findByHql(issb);
        if(rec!=null && rec.size()>0){
            throw new Exception("设备已被使用");
        }
        //领用设备
        Receive receive = new Receive();
        receive.setMatch(deviceMatch);
        receive.setEquipmentName(equipmentStorageDetail.getEquipmentName());
        receive.setEmanufacturerName(equipmentStorageDetail.getManufacturerName());
        receive.setEspecification(equipmentStorageDetail.getEspecification());
        receive.setEsN(equipmentStorageDetail.getsN());
        receive.setNetworkName(deviceMatch.getSimdetail().getNerworkName());
        receive.setSmanufacturerName(deviceMatch.getSimdetail().getManufacturerName());
        receive.setSsN(deviceMatch.getSimdetail().getsN());
        receive.setRecord(personRecord);
        receive.setRemark("扫码领用");
        List<User> users = baseDao.findByHql("from User where uname='admin'");
        if(users==null || users.isEmpty()){
            throw new Exception("扫码操作员不存在");
        }
        receive.setCreateUser(users.get(0));
        receive.setCreateTime(new Date());
        ReceiveRecipt receipt = new ReceiveRecipt();
        receipt.setCreateTime(new Date());
        receipt.setReceiptUser(users.get(0));
        receipt.setMoney(0);
        Set res = new HashSet<ReceiveRecipt>();
        res.add(receipt);
        receive.setReceipts(res);
        int rid = 0;
        //保存领用记录
        if((rid = baseDao.addNumKey(receive))>0){
            EquipmentLeader leader = new EquipmentLeader();
            leader.setCreateTime(new Date());
            leader.setCreateUser(users.get(0));
            leader.setReceive(receive);
            leader.setRecord(personRecord);
            leader.setUserNo("1");//设置用户编号1...n
            if(!baseDao.add(leader)){
                throw new Exception("绑定设备用户失败");
            }
            if(equipmentStorageDetail.getEquipmentName().equals("血压计")){
                //绑定第二用户
                if(!StringUtils.isEmpty(bindInfo.getOtheridcard())){
                    List<PersonRecord> opersonRecords = baseDao.findByHql("from PersonRecord pr where pr.idcard='"+bindInfo.getOtheridcard()+"'");
                    PersonRecord opersonRecord = null;
                    if(opersonRecords==null || opersonRecords.isEmpty()){
                        System.out.println("用户在系统中不存在，先注册档案");
                        opersonRecord = new PersonRecord();
                        opersonRecord.setName(bindInfo.getOtherUserName());
                        opersonRecord.setIdcard(bindInfo.getOtheridcard());
                        int pid = 0;
                        if((pid=baseDao.addNumKey(opersonRecord))<=0){
                            throw new Exception("注册档案失败");
                        }
                        opersonRecord.setId(pid);
                    }else{
                        opersonRecord = opersonRecords.get(0);
                    }
                    EquipmentLeader leader1 = new EquipmentLeader();
                    leader1.setCreateTime(new Date());
                    leader1.setCreateUser(users.get(0));
                    leader1.setReceive(receive);
                    leader1.setRecord(opersonRecord);
                    leader1.setUserNo("2");//设置用户编号1...n
                    if(!baseDao.add(leader1)){
                        throw new Exception("绑定设备用户失败");
                    }
                }
            }

            /**********保存设备-用户绑定记录结束********************/

            // 更改库存信息状态
            String hql = "update EquipmentStorageDetail set equipmentStatus.id=2 where id="+equipmentStorageDetail.getId();
            if(!baseDao.editHql(hql)){
                throw new Exception("更新设备使用状态失败");
            }
            //更新设备库存数
            hql = "update EquipmentStorage set stockNumber = stockNumber-1 where id = ("
                    + "select equipmentStorage.id from EquipmentStorageDetail where id="+equipmentStorageDetail.getId()+")";
            if(!baseDao.editHql(hql)){
                throw new Exception("更新设备库存失败");
            }

            String simhql = "update SimStorageDetail set equipmentStatus.id=2 where id="+receive.getMatch().getSimdetail().getId();
            if(!baseDao.editHql(simhql)){
                throw new Exception("更新SIM卡使用状态失败");
            }
            //更新SIM卡库存数
            simhql = "update SimStorage set stockNumber = stockNumber-1 where id = ("
                    + "select simStorage.id from SimStorageDetail where id="+receive.getMatch().getSimdetail().getId()+")";
            if(!baseDao.editHql(simhql)){
                throw new Exception("更新SIM卡库存失败");
            }
        }else{
            throw new Exception("保存领用信息失败");
        }
        return ResponseData.ok();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseData bindotherfromsm(BindInfo bindInfo) throws Exception {
        //查询用户是否存在
        List<PersonRecord> personRecords = baseDao.findByHql("from PersonRecord pr where pr.idcard='"+bindInfo.getOtheridcard()+"'");
        PersonRecord personRecord = null;
        if(personRecords==null || personRecords.isEmpty()){
            System.out.println("用户在系统中不存在，先注册档案");
            personRecord = new PersonRecord();
            personRecord.setName(bindInfo.getOtherUserName());
            personRecord.setIdcard(bindInfo.getOtheridcard());
            int pid = 0;
            if((pid=baseDao.addNumKey(personRecord))<=0){
                throw new Exception("注册档案失败");
            }
            personRecord.setId(pid);
        }else{
            personRecord = personRecords.get(0);
        }
        //查询设备是否存在
        List<EquipmentStorageDetail> equipmentStorageDetails = baseDao.findByHql("from EquipmentStorageDetail edetail where edetail.sN='"+bindInfo.getSn()+"'");
        if(equipmentStorageDetails==null || equipmentStorageDetails.isEmpty()){
            throw new Exception("设备不存在");
        }
        EquipmentStorageDetail equipmentStorageDetail = equipmentStorageDetails.get(0);

        //设备是否已经被领用
        List<Receive> receives = baseDao.findByHql("from Receive where esN='"+bindInfo.getSn()+"' and (receiveTime=null or receiveTime='')");
        if(receives==null || receives.isEmpty()){
            throw new Exception("设备未曾被领用");
        }
        String userNo = "1";
        //查询设备绑定记录
        List<EquipmentLeader> equipmentLeaders = baseDao.findByHql("from EquipmentLeader where receive.id="+receives.get(0).getId());
        if(equipmentLeaders==null || equipmentLeaders.isEmpty()){
            userNo = "1";
        }else if(equipmentLeaders.size() == 1){
            if(!equipmentStorageDetail.getEquipmentName().equals("血压计")){
                throw new Exception("该型设备无法绑定第二用户");
            }
            userNo = "2";
        }else{
            throw new Exception("设备已经绑定了超过两个用户，无法继续绑定");
        }
        //查询用户是否已经领用了同类型的设备
        String ishas = "from Receive where record.id="+personRecord.getId()+" and receiveTime=null and " +
                "match.equipmentdetail.equipmentStorage.equipment.kind.id=" +
                "(select dm.equipmentStorage.equipment.kind.id from EquipmentStorageDetail dm where dm.id="+equipmentStorageDetail.getId()+")";
        List rs = baseDao.findByHql(ishas);
        if(rs!=null && !rs.isEmpty()){
            throw new Exception("用户已经领取了该类型的设备，请退还后在申请");
        }

        List<User> users = baseDao.findByHql("from User where uname='sm'");
        if(users==null || users.isEmpty()){
            throw new Exception("扫码操作员不存在");
        }
        EquipmentLeader leader = new EquipmentLeader();
        leader.setCreateTime(new Date());
        leader.setCreateUser(users.get(0));
        leader.setReceive(receives.get(0));
        leader.setRecord(personRecord);
        leader.setUserNo(userNo);//设置用户编号1...n
        if(!baseDao.add(leader)){
            throw new Exception("绑定设备用户失败");
        }
        return ResponseData.ok();
    }
}
